package com.xincongjun.media.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.stream.Collectors;

public class PowerShellUtil {

    private static final Logger logger = LoggerFactory.getLogger(PowerShellUtil.class);

    public static void usePowerShellUpdateTime(String filePath, String creationTime, String lastWriteTime, String lastAccessTime) {
        String escapedFilePath = filePath.replace("'", "''");

        String psCommand = String.format(
                "$f = Get-Item '%s'; $f.CreationTime = [datetime]::Parse('%s'); $f.LastWriteTime = [datetime]::Parse('%s'); $f.LastAccessTime = [datetime]::Parse('%s')",
                escapedFilePath, creationTime, lastWriteTime, lastAccessTime
        );
        ProcessBuilder builder = new ProcessBuilder("powershell.exe", "-Command", psCommand);
        builder.redirectErrorStream(true);

        try {
            Process process = builder.start();

            String output;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")))) {
                output = reader.lines().collect(Collectors.joining(System.lineSeparator()));
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("执行 PowerShell 命令失败：" + filePath + "\n" + output);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void usePowerShellUpdateTime(String filePath, String timeString) {
        String escapedFilePath = filePath.replace("'", "''");

        String psCommand = String.format(
                "$f = Get-Item '%s'; $f.CreationTime = [datetime]::Parse('%s'); $f.LastWriteTime = [datetime]::Parse('%s'); $f.LastAccessTime = [datetime]::Parse('%s')",
                escapedFilePath, timeString, timeString, timeString
        );
        ProcessBuilder builder = new ProcessBuilder("powershell.exe", "-Command", psCommand);
        builder.redirectErrorStream(true);

        try {
            Process process = builder.start();

            String output;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")))) {
                output = reader.lines().collect(Collectors.joining(System.lineSeparator()));
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("执行 PowerShell 命令失败：" + filePath + "\n" + output);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}

